package com.example.greentrack;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_BEHAVIOR = 1;
    private TextView tvTotalCO2;
    private double totalSavedCO2 = 0; // 初始值

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvTotalCO2 = findViewById(R.id.tv_total_co2);
        Button btnBehavior = findViewById(R.id.btn_behavior);
        Button btnCarbon = findViewById(R.id.btn_carbon);
        Button btnLogout = findViewById(R.id.btn_logout);

        updateCO2Display();

        btnBehavior.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 使用startActivityForResult启动BehaviorActivity
                Intent intent = new Intent(MainActivity.this, BehaviorActivity.class);
                startActivityForResult(intent, REQUEST_CODE_BEHAVIOR);
            }
        });

        btnCarbon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, CarbonActivity.class));
            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_BEHAVIOR && resultCode == RESULT_OK) {
            if (data != null) {
                double newCO2 = data.getDoubleExtra("total_co2", 0.0);
                totalSavedCO2 += newCO2;
                updateCO2Display();
            }
        }
    }

    private void updateCO2Display() {
        tvTotalCO2.setText(String.format("累计节省: %.1fkg CO₂", totalSavedCO2));
    }
}